from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Enum
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.database import Base
import enum


class ExamStatus(enum.Enum):
    DRAFT = "draft"
    PUBLISHED = "published"
    ONGOING = "ongoing"
    COMPLETED = "completed"
    CANCELLED = "cancelled"


class ExamType(enum.Enum):
    PRACTICE = "practice"  # 练习模式
    FORMAL = "formal"      # 正式考试


class Exam(Base):
    __tablename__ = "exams"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(200), nullable=False)
    description = Column(Text)
    duration = Column(Integer, nullable=False)  # 考试时长（分钟）
    total_score = Column(Integer, default=100)
    pass_score = Column(Integer, default=60)
    start_time = Column(DateTime(timezone=True), nullable=False)
    end_time = Column(DateTime(timezone=True), nullable=False)
    status = Column(Enum(ExamStatus), default=ExamStatus.DRAFT, nullable=False)
    exam_type = Column(Enum(ExamType), default=ExamType.FORMAL, nullable=False)
    question_count = Column(Integer, default=0)
    created_by = Column(Integer, ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    is_deleted = Column(Boolean, default=False)
    is_shuffle = Column(Boolean, default=True)  # 是否随机打乱题目顺序
    allow_review = Column(Boolean, default=True)  # 是否允许回顾答案
    
    # 关系
    creator = relationship("User", back_populates="created_exams")
    questions = relationship("Question", back_populates="exam", cascade="all, delete-orphan")
    scores = relationship("Score", back_populates="exam")
    logs = relationship("Log", back_populates="exam")